<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Action\Dashboard;

use _PHPStan_b8e553790\Nette\Neon\Exception;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\IndexLogic;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 客户标签创建
 * @Controller
 */
class ClientLabelIndex extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/client/labelIndex", methods="GET")
     */
    public function handle()
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        $data = $this->request->all();
        $list = Db::table('client_label_group as g')
            ->leftJoin('client_label as l', 'l.client_label_group_id', '=', 'g.id')
            ->select([
                'g.name as groupName',
                'g.id',
                'g.order',
                'l.name as labelName',
                'l.order as labelOrder',
                'l.id as labelId',
                'l.client_label_group_id as contactTagGroupId',
            ])->get();
        $newList = [];
        $count = 0;
        $labels = [];
        $list || $list = collect([]);
        $list = $list->toArray();

        if (empty($list)) {
            return ['count' => $count, 'list' => $newList];
        }

        foreach ($list as &$item) {
            $count += 1;
            $labels[$item->id][] = [
                'name' => $item->labelName,
                'order' => $item->labelOrder,
                'id' => $item->labelId,
                'contactTagGroupId' => $item->contactTagGroupId,
            ];
            $order = array_column($labels[$item->id], 'order');
            $key = array_column($labels[$item->id], 'id');
            array_multisort($order, SORT_ASC, $key, SORT_DESC, $labels[$item->id]);
            $newList[$item->id] = [
                'groupName' => $item->groupName,
                'id' => $item->id,
                'order' => $item->order,
                'tags' => $labels[$item->id],
            ];
        }
        //$newList排序按照order字段倒序
        $order = array_column($newList, 'order');
        $key = array_column($newList, 'id');

        array_multisort($order, SORT_ASC, $key, SORT_DESC, $newList);
        return ['count' => $count, 'list' => $newList];
    }
}
